package com.peanut.baby.mvp.profileedit;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;

import androidx.annotation.NonNull;

import com.peanut.baby.InitManager;
import com.peanut.baby.http.BaseObserver;
import com.peanut.baby.http.BaseResponse;
import com.peanut.baby.http.BaseScheduler;
import com.peanut.baby.http.RetrofitClient;
import com.peanut.baby.model.AuthrizeInfo;
import com.peanut.baby.model.UploadConf;
import com.peanut.baby.model.User;
import com.peanut.baby.uploader.UploadMgr;
import com.peanut.devlibrary.compressor.Compressor;
import com.peanut.devlibrary.util.DeviceInfo;
import com.peanut.devlibrary.util.StringUtil;
import com.tencent.mars.xlog.Log;
import com.yanzhenjie.alertdialog.AlertDialog;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.nekocode.rxlifecycle.RxLifecycle;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.friends.Wechat;
import io.reactivex.Observable;

import static android.content.ContentValues.TAG;

/**
 * Created by anonymouslystudio on 2017/7/17.
 */

public class ProfileEditPresenter implements ProfileEditContract.Presenter{
    private PlatformActionListener listener;

    private ProfileEditContract.View    view;
    Activity activity;
    public ProfileEditPresenter(ProfileEditContract.View view,Activity activity){
        this.view = view;
        this.activity = activity;
    }
    @Override
    public void checkPermission(final Activity ctx) {
        AndPermission.with(ctx)
                .requestCode(100)
                .permission(Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .rationale(new RationaleListener(){

                    @Override
                    public void showRequestPermissionRationale(int requestCode, final Rationale rationale) {
                        AlertDialog.newBuilder(ctx)
                                .setTitle("提醒")
                                .setMessage("读取本地图片需要您授予对应的权限")
                                .setPositiveButton("授予", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        rationale.resume();
                                    }
                                })
                                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        rationale.cancel();
                                    }
                                })
                                .show();
                    }
                })
                .callback(new PermissionListener() {
                    @Override
                    public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                        Log.d("LauncherActivity","PermissionListener.SUCCESS");
                        view.onPermissionGranted(grantPermissions);
                    }

                    @Override
                    public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
                        Log.d("LauncherActivity","PermissionListener.FAIL");
                        view.onPermissionDenied(deniedPermissions);
                    }
                })
                .start();
    }

    @Override
    public void compressAndUploadPhoto(final String path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                File compressed = Compressor.compress(new File(path));
                UploadMgr.getInstance().uploadImage(compressed.getAbsolutePath(),
                        UploadMgr.UPLOAD_TYPE_AVATAR, InitManager.getInstance().getUserId(), new UploadMgr.UploadListener() {
                            @Override
                            public void onQueryToken() {
                            }

                            @Override
                            public void onStartUpload() {

                            }

                            @Override
                            public void onUploadProgress(int total) {

                            }

                            @Override
                            public void onUploadSuccess(UploadConf config) {
                                view.onPictureUploadFinished(true,"",config);
                            }

                            @Override
                            public void onUploadFailed(UploadConf config,String failed) {
                                view.onPictureUploadFinished(false,failed,config);
                            }
                        });
            }
        }).start();
    }

    @Override
    public void updateUserInfo(String newAvatar, String newNick, String newGender,String sign,int newAge,String newProvince,int userStatus) {
        Map<String,String> params = new HashMap<>();
        params.put("userToken",InitManager.getInstance().getUser().userToken);
        params.put("nickname",newNick);
        params.put("gender",newGender);
        params.put("avatar",newAvatar);
        params.put("signStr",sign);
        params.put("age",newAge+"");
        params.put("province",newProvince);
        params.put("userStatus",userStatus+"");
        Observable observable = RetrofitClient.getInstance().updateUserInfo(params);
        observable.compose(BaseScheduler.<BaseResponse<User>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<User>() {
            @Override
            protected void onHandleSuccess(User o) {
                InitManager.getInstance().getUser().nickname = o.nickname;
                InitManager.getInstance().getUser().gender = o.gender;
                InitManager.getInstance().getUser().avatar = o.avatar;
                InitManager.getInstance().getUser().age = o.age;
                InitManager.getInstance().getUser().province = o.province;
                InitManager.getInstance().getUser().sign = o.sign;
                InitManager.getInstance().getUser().userType = o.userType;
                InitManager.getInstance().getUser().userStatus = o.userStatus;
                InitManager.getInstance().updateLocalUser();
                Log.d("AAA","profile updated");
                view.onUpdateInfoSuccess();
            }

            @Override
            protected void onHandleError(String code,String msg) {
                view.onRequestFailed(code,msg);
            }

        });
    }

    @Override
    public void wxAuth() {
        Platform platform = ShareSDK.getPlatform(Wechat.NAME);
        if(platform != null){
            if(platform.isAuthValid()){
                platform.removeAccount(true);
            }
            if(listener == null){
                listener = new PlatformLoginListener();
            }
            Log.d(TAG,"listener == null? "+(listener == null));
            platform.setPlatformActionListener(listener);
            platform.showUser(null);
        }
    }

    @Override
    public void bindWeixin(final String openId, String accessToken, String expireIn, String unionId) {
        Observable observable = RetrofitClient.getInstance().bindWeixin(InitManager.getInstance().getUserId(),
                InitManager.getInstance().getUser().userToken,
                accessToken,expireIn,openId,unionId);
        observable.compose(BaseScheduler.<BaseResponse<User>>compose())
                .compose(RxLifecycle.bind(activity).withObservable())
                .subscribe(new BaseObserver<User>() {
                    @Override
                    protected void onHandleSuccess(User o) {
                        InitManager.getInstance().getUser().openid = openId;
                        InitManager.getInstance().updateLocalUser();
                        view.onBindWeixinSuccess();
                    }

                    @Override
                    protected void onHandleError(String code,String msg) {
                        view.onRequestFailed(code,"绑定失败 "+msg);
                    }

                });
    }

    class PlatformLoginListener implements PlatformActionListener {

        @Override
        public void onComplete(Platform platform, int i, HashMap<String, Object> res) {
            //解析部分用户资料字段
            Log.d(TAG,"onComplete: "+i+" "+platform.getName()) ;

            Log.d(TAG,"ACTION_USER_INFOR");

            PlatformDb platDB = platform.getDb();//获取数平台数据DB
            Log.d(TAG,"platDB is null "+(platDB == null)+" isValid  "+platDB.isValid());
            final AuthrizeInfo info;

            if(platDB != null && platDB.isValid()) {
                info = new AuthrizeInfo();
                info.accessToken = platDB.getToken();
                info.expireIn = platDB.getExpiresTime();
                info.openId = platDB.getUserId();


                info.type = AuthrizeInfo.TYPE_WEIXIN;
                info.unionid = res.get("unionid").toString();

                if (res.containsKey("headimgurl")) {
                    info.avatar = res.get("headimgurl").toString();
                }

                if (res.containsKey("nickname")) {
                    info.nickname = res.get("nickname").toString();
                }

                if (res.containsKey("country")) {
                    info.country = res.get("country").toString();
                }

                if (res.containsKey("city")) {
                    info.city = res.get("city").toString();
                }

                if (res.containsKey("province")) {
                    info.province = res.get("province").toString();
                }
                info.gender = platDB.getUserGender();
                if(StringUtil.isNullOrEmpty(info.gender)){
                    info.gender = User.GENDER_MALE;
                }else{
                    if(info.gender.equals("0") || info.gender.equals("m")){
                        info.gender = User.GENDER_MALE;
                    }else{
                        info.gender = User.GENDER_FEMALE;
                    }
                }

                Log.d(TAG, "A" + info.toString());

                info.uuid = InitManager.getInstance().info.uuid;
                info.mac = InitManager.getInstance().info.mac;
                info.ipAddress = InitManager.getInstance().info.ip;
                info.device = DeviceInfo.device;
                info.osversion = DeviceInfo.osversion;
                info.model = DeviceInfo.model;
                info.version = InitManager.getInstance().info.appversion;
                info.screen = InitManager.getInstance().info.screen;
                info.network = InitManager.getInstance().info.network;
                Log.d(TAG, "onAuthSuccess" + info.toString());
                view.onAuthSuccess(info);
            }else{
                Log.d(TAG,"get auth info failed");
                view.onRequestFailed("-1","无法获取授权信息");
            }
        }

        @Override
        public void onError(Platform platform, int i, Throwable throwable) {
            view.onRequestFailed("-1","授权失败 "+throwable.toString());
        }

        @Override
        public void onCancel(Platform platform, int i) {
            view.onRequestFailed("-1","用户取消授权 ");
        }


    }

    public void onDestory(){
        listener = null;
    }
}
